package wsp.dailymarket.deals;

import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;

/**
 * Creates the pagination links at the bottom of each deal list page
 * @author Matt
 */
@FacesRenderer(componentFamily = "javax.faces.Command", rendererType = "wsp.dailymarket.deals.DealPaginator")
public class DealPaginatorRenderer extends Renderer {

	private DealViewBean dealViewBean;

	@Override
	public void encodeBegin(FacesContext context, UIComponent component)
			throws IOException {

		ResponseWriter writer = context.getResponseWriter();

		dealViewBean = (DealViewBean) context.getExternalContext().getRequestMap().get("dealView");

		String styleClass = (String) component.getAttributes().get("styleClass");
		String selectedStyleClass = (String) component.getAttributes().get("selectedStyleClass");
		int showpages = toInt(component.getAttributes().get("showPages"));

		int currentPage = dealViewBean.getCurrentPage();
		int maxPages = dealViewBean.getMaxPages();

		int startPage = 1;
		int endPage = maxPages;
		if (showpages > 0) {
			startPage = ((currentPage / showpages) * showpages) + 1;
			endPage = Math.min(startPage + showpages, maxPages);
		}
		if (currentPage > 1) {
			this.writeLink(writer, component, "<", styleClass, currentPage - 1);
		}

		if (startPage > 1) {
			int back_a_lot = currentPage - showpages;
			if (back_a_lot < 1) {
				back_a_lot = 1;
			}
			this.writeLink(writer, component, "<<", styleClass, back_a_lot);
		}

		for (int i = startPage; i <= endPage; i++) {
			this.writeLink(writer, component, "" + i, i == currentPage ? selectedStyleClass : styleClass, i);
		}

		if (endPage < maxPages) {
			int forward_a_lot = currentPage + showpages;
			if (forward_a_lot > maxPages) {
				forward_a_lot = maxPages;
			}
			this.writeLink(writer, component, ">>", styleClass, forward_a_lot);
		}

		if (currentPage < maxPages) {
			this.writeLink(writer, component, ">", styleClass, currentPage + 1);
		}

	}

	private void writeLink(ResponseWriter writer, UIComponent component,
			String linkText, String styleClass, int targetPage)
			throws IOException {
		writer.writeText(" ", null);
		writer.startElement("a", component);
		writer.writeAttribute("href", dealViewBean.buildRestLink("page", String.valueOf(targetPage)), null);
		if (styleClass != null) {
			writer.writeAttribute("class", styleClass, "styleClass");
		}
		writer.writeText(linkText, null);
		writer.endElement("a");
	}

	private static int toInt(Object value) {
		if (value == null) {
			return 0;
		}
		if (value instanceof Number) {
			return ((Number) value).intValue();
		}
		if (value instanceof String) {
			return Integer.parseInt((String) value);
		}
		throw new IllegalArgumentException("Cannot convert " + value);
	}
}
